package com.sreManager.controller.web;

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.sreManager.Constant;
import com.sreManager.domain.CompanyBuildingDao;
import com.sreManager.domain.CompanyEstimate;
import com.sreManager.domain.CompanyIncharge;
import com.sreManager.domain.LoginUsers;
import com.sreManager.mapper.CompanyBuildingMapper;
import com.sreManager.model.BuildingModel;
import com.sreManager.service.BuildingService;
import com.sreManager.web.util.CommonUtil;
import com.sreManager.web.util.LoginManager;

@Controller
@RequestMapping(value={"/"})
public class BuildingController extends CommonController{
	@Autowired CompanyBuildingMapper buildingMapper;
	@Autowired BuildingService buildingService;
	String TILESForder = "building";
	@ModelAttribute("menuType")
	public String type(){
		return TILESForder;
	}
	/**
	 * 리스트
	 * @return
	 * @throws UnknownHostException
	 */
	@RequestMapping(value={"search"})
	public String list(Model model, @RequestParam HashMap<String, Object> paramMap, @RequestParam(required=false) String logMsg) throws UnknownHostException{

		Integer pageDataTotal = buildingMapper.selectBuildingPagingCount(paramMap);
		model.addAttribute("pageDataTotal", pageDataTotal);
    	if(pageDataTotal!=null && pageDataTotal > 0){
    		paramMap = CommonUtil.pagingNumCheck(paramMap, pageDataTotal);
    		paramMap.put("USER_ROLE_GROUP", Constant.USER_ROLE);
    		paramMap.put("USER_STATE_GROUP", Constant.USER_STATE);
    		model.addAttribute("pagingList", buildingMapper.selectBuildingPagingList(paramMap));
    	}
		model.addAttribute("pageParam", paramMap);

		paramMap = new HashMap<String, Object>();
		paramMap.put("group", Constant.MEASURE_TARGET);
		model.addAttribute("measureTargetList", codeMapper.selectCodeList(paramMap));

		// 로그인 유저 정보
		LoginUsers loginUser = LoginManager.getInstance().getSession(request);

		String logMenu=Constant.MENU_SEARCH;
        if(!loginUser.getRole().equals(Constant.USER)){
			logMenu = Constant.MENU_COMPANY;
		}
		// 로그
		if(logMsg != null){
			logsService.insertLog(request, Constant.LOG_TYPE_SEARCH, logMenu, logMsg);
		}else{
			logsService.insertLog(request, Constant.LOG_TYPE_LIST, logMenu);
		}
		return TILESForder+"/list"+Constant.TILES;
	}

	/**
	 * 상세보기
	 * @return
	 * @throws UnknownHostException
	 */
	@RequestMapping(value={"form"}, method=RequestMethod.GET)
	public String form(Model model, @RequestParam(required=false) Integer buildingCd, @ModelAttribute BuildingModel buildingModel, @RequestParam(required=false) String logMsg) throws UnknownHostException {

    	HashMap<String, Object> paramMap = new HashMap<String, Object>();
    	CompanyBuildingDao buildingDao = new CompanyBuildingDao();

		// 로그인 유저 정보
		LoginUsers loginUser = LoginManager.getInstance().getSession(request);

		// 로그
		String logType = "";

    	if(loginUser.getRole().equals(Constant.USER) && buildingCd==null){
			return "redirect:/unuse";
    	}else if (buildingCd!=null) {
    		paramMap.put("buildingCd", buildingCd);
    		buildingDao = buildingMapper.selectBuilding(paramMap);

    		if(buildingDao.getIncharge() == null || buildingDao.getIncharge().size() == 0){
    			List<CompanyIncharge> incharge = new ArrayList<CompanyIncharge>();
    			incharge.add(new CompanyIncharge());
    			buildingDao.setIncharge(incharge);
    		}

    		if(buildingDao.getEstimate() == null || buildingDao.getEstimate().size() == 0){
    			List<CompanyEstimate> estimates = new ArrayList<CompanyEstimate>();
            	estimates.add(new CompanyEstimate());
            	buildingDao.setEstimate(estimates);
    		}

    		// 로그
    		logType = Constant.LOG_TYPE_VIEW;

        }else{
        	buildingDao = new CompanyBuildingDao();
        	List<CompanyIncharge> incharge = new ArrayList<CompanyIncharge>();
        	incharge.add(new CompanyIncharge());
        	buildingDao.setIncharge(incharge);
        	List<CompanyEstimate> estimates = new ArrayList<CompanyEstimate>();
        	estimates.add(new CompanyEstimate());
        	buildingDao.setEstimate(estimates);
        }

        buildingModel.setBuildingDao(buildingDao);


        if(!loginUser.getRole().equals(Constant.USER)){
    		model = formItem(model, paramMap);

    		if(logType!=null) {
    			// 로그
    			logsService.insertLog(request, logType, Constant.MENU_COMPANY, logMsg);
    		}
    		return TILESForder+"/form"+Constant.TILES;
		}else{
			// 로그
			logsService.insertLog(request, logType, Constant.MENU_SEARCH, logMsg);

			return TILESForder+"/view"+Constant.TILES;
		}
	}

	private Model formItem(Model model, HashMap<String, Object> paramMap) {

		paramMap = new HashMap<String, Object>();
		paramMap.put("group", Constant.MEASURE_TARGET);
		model.addAttribute("measureTargetList", codeMapper.selectCodeList(paramMap));
		paramMap.put("group", Constant.MEASURE_TYPE);
		model.addAttribute("measureTypeList", codeMapper.selectCodeList(paramMap));
		paramMap.put("group", Constant.ESTIMAT_SURTAX);
		model.addAttribute("estimatSurtaxList", codeMapper.selectCodeList(paramMap));

		return model;
	}

    /**
     * 서비스 관리 - 등록 및 수정 submit
     * @param cmd
     * @param serviceModel
     * @param result
     * @param model
     * @param locale
     * @param request
     * @return
     * @throws UnknownHostException
     */
    @RequestMapping(value="form", method=RequestMethod.POST)
    public String formSubmit(@Valid @ModelAttribute BuildingModel buildingModel
            , BindingResult result
            , Model model
            , Locale locale
            , HttpServletRequest request
            , @RequestParam(required=false) String logMsg
            ) throws UnknownHostException {
    	HashMap<String, Object> paramMap = new HashMap<String, Object>();
        if (result.hasFieldErrors()){
    		// 등록 및 수정에서 사용하는 item
    		model = formItem(model, paramMap);
        	return TILESForder+"/form"+Constant.TILES;
        }

        if (buildingModel.getBuildingDao().getBuildingCd()!=null) {
        	buildingService.update(buildingModel);

    		// 로그
    		logsService.insertLog(request, Constant.LOG_TYPE_MOD, Constant.MENU_COMPANY, logMsg);

        } else {
        	buildingService.insert(buildingModel);

    		// 로그
    		logsService.insertLog(request, Constant.LOG_TYPE_REG, Constant.MENU_COMPANY, logMsg);

        }
		// 등록 및 수정에서 사용하는 item
		model = formItem(model, paramMap);
        return TILESForder+"/form"+Constant.TILES;
    }

}
